package cn.chowx.myjfinal.system.model;

import org.apache.commons.lang3.math.NumberUtils;

import cn.chowx.myjfinal.common.TableName;

import com.jfinal.plugin.activerecord.Model;

/**
 * 用户-角色映射
 * @author zcqshine
 *
 */
@SuppressWarnings("serial")
public class SysUserRole extends Model<SysUserRole> {
	public static final SysUserRole DAO = new SysUserRole();
	private static final int STATUS_VALIABLE = 1;  //有效状态
	private static final int STATUS_UNVALIABLE = 0; //无效状态
	
	/**
	 * 增加或者更新用户拥有的角色. 操作成功返回 true, 失败返回 false
	 * @param uid
	 * @param keyValues roleId:checked 键值对
	 */
	public boolean saveOrUpdate(int uid, String[] keyValues){
		boolean flag = false;
		for(String kv : keyValues){
			int roleId = NumberUtils.toInt(kv.split(":")[0]);
			boolean checked = Boolean.parseBoolean(kv.split(":")[1]);
			SysUserRole ur = getUserRoleByUidAndRid(uid, roleId);
			if(ur != null){
				ur.set("status",checked?STATUS_VALIABLE:STATUS_UNVALIABLE);
				flag = ur.update();
			}else{
				ur = new SysUserRole();
				ur.set("userId", uid);
				ur.set("roleId", roleId);
				flag = ur.save();
			}
			if(!flag){
				return flag;
			}
		}
		
		return flag;
	}
	
	/**
	 * 根据用户 id 和角色 id 查找用户-角色映射关系
	 * @param uid
	 * @param roleId
	 * @return
	 */
	private SysUserRole getUserRoleByUidAndRid(int uid, int roleId){
		return findFirst("select * from " + TableName.SysUserRole.getTableName() + " where userId=? and roleId = ?", uid, roleId);
	}
}
